const fs = require("fs");
const path = require('path')
const mammoth = require('mammoth');
const database = require('../../database/sqliteCRUD/index')
let dirPath = `D:\\document\\电影解说稿3万份(43)`


async function readDir(dirPath) {
    let dirCont = fs.readdirSync(dirPath, {encoding: 'utf-8'})
    for (let i = 0; i < dirCont.length; i++) {
        let fullPath = path.join(dirPath, dirCont[i])
        if (fs.statSync(fullPath).isDirectory()) {
            console.log(`${fullPath}  是文件夹 进行递归`);
            await readDir(fullPath)
        } else if (fs.statSync(fullPath).isFile()) {

            let str = await readFile(fullPath); // 读取并打印文件内容
            let sql = `insert into sentence (word, time) values (?, ?)`

            console.log(rows)
        } else {
            console.log(fullPath, '未知错误')
            break;
        }
    }

}


function writeFile(filename, str) {
    let textDir = path.join(__dirname, `text`)
    if (!fs.existsSync(textDir)) fs.mkdirSync(path.join(__dirname, `text`))
    try {
        fs.writeFileSync(path.join(textDir, `/${filename}.txt`), str, {encoding: 'utf-8'})
    } catch (e) {
        throw e
    }


}

async function readFile(filePath) {

    if (filePath.includes('.docx')) {
        let buffer = fs.readFileSync(filePath)
        let res = await mammoth.convertToHtml({buffer})
        if (Object.keys(res).includes('value')) return res.value
    }
    if (filePath.includes('.txt')) return fs.readFileSync(filePath, 'utf-8')
    return null
}

// 调用函数，开始递归读取目录
readDir(dirPath).then(r => {
    console.log(`完成`);
});

if (fs.existsSync(dirPath)) {

    /**
     * root = "D:\"
     * dir = "D:\document\电影解说稿3万份(43)\精品电影解说稿1000"
     * base = "治愈电影《澄沙之味》解说文案.docx"
     * ext = ".docx"
     * name = "治愈电影《澄沙之味》解说文案"
     * @type {string}
     */


}